<template>
  <!-- 浙政钉选择用户 -->
  <el-dialog
    title="浙政钉选择用户"
    v-model="visibleDialog"
    width="1200px"
    top="5vh"
  >
    <div class="container">
      <div class="page-main">
        <div class="page-main-query">
          <filter-bar
            v-model:query="query"
            @search="handleSearch"
            @reset="reset"
          />
        </div>
        <section class="content">
          <div class="org-tree">
            <el-scrollbar style="height: 100%">
              <org-tree :disabled="loading" @select="handleSelectOrg" />
            </el-scrollbar>
          </div>
          <div class="table-card">
            <vxe-grid
              height="100%"
              v-loading="loading"
              ref="xGrid"
              :columns="columns"
              :data="userData"
              size="mini"
              border
              rowKey
              :expand-config="{
                accordion: true,
              }"
              @toggle-row-expand="expandUserDetail"
            >
              <template #expand="{ row }">
                <h5>所在组织及角色</h5>
                <div
                  v-if="row.orgRoleList && row.orgRoleList.length > 0"
                  class="org-role-panel"
                >
                  <div v-for="item in row.orgRoleList" :key="item.id">
                    <span>{{ item.orgName }}: </span>
                    <el-tag v-if="item.roleName">{{ item.roleName }}</el-tag>
                    <span>暂无角色</span>
                  </div>
                </div>
                <div class="org-role-panel" v-else>暂无组织</div>
              </template>
              <template #avatar="{ row }">
                <el-avatar
                  shape="square"
                  icon="el-icon-user-solid"
                  size="small"
                >
                  <img v-if="row.avatar" :src="row.avatar" alt="" />
                  <i v-else class="el-icon-user-solid"></i>
                </el-avatar>
              </template>
              <template #actions="{ row }">
                <!-- <el-button type="text" @click="handlePassword(row)">
                编辑密码
              </el-button> -->
                <el-button type="text" @click="sureSelectUser(row, true)">
                  选择
                </el-button>
              </template>
            </vxe-grid>

            <footer>
              <el-pagination
                :background="true"
                @size-change="sizeChange"
                @current-change="getUserList"
                v-model:currentPage="query.current"
                :page-sizes="[20, 50, 100, 200]"
                :page-size="query.size"
                layout="sizes, prev, pager, next"
                :total="total"
              />
            </footer>
          </div>
        </section>
      </div>

      <edit-dialog ref="dialogRef" @update-list="getUserList" />
    </div>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, onMounted, toRefs, computed } from "vue";
import {
  getUsers,
  getUserInfo,
  unbindPhone,
  removeUser,
  editUser,
} from "@/api/system";
import DynamicTable from "@/components/DynamicTable";
import FilterBar from "./components/FilterBar.vue";
import OrgTree from "./components/OrgTree.vue";
import EditDialog from "./components/EditDialog.vue";
import Header from "@/components/Header.vue";
import { ElMessageBox, ElMessage } from "element-plus";
const emit = defineEmits(["update:modelValue", "query-change"]);
const dialogRef = ref(null);
const loading = ref(false);
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
});

const visibleDialog = computed({
  get: () => props.modelValue,
  set: (val) => {
    console.log(val);
    emit("update:modelValue", val);
  },
});

// 确认选择
const sureSelectUser = (row, flag) => {
  emit("query-change", row);
};

//查询条件
const query = reactive({
  userName: "",
  mobile: "",
  orgId: "",
  current: 1,
  size: 20,
});
const total = ref(0);
const columns = ref([
  // 表格列配置
  {
    width: 50,
    align: "center",
    title: "",
    type: "expand",
    slots: { content: "expand" },
  },
  // {
  //   width: 50,
  //   title: "头像",
  //   slots: { default: "avatar" },
  //   className: "avatar-cell",
  // },
  { field: "accountId", title: "浙政钉ID" },
  { field: "userName", title: "姓名" },
  { field: "mobile", title: "手机号码" },
  { width: 100, title: "操作", slots: { default: "actions" } },
]);
const userData = ref([]); // 用户数据

// 点击组织
const handleSelectOrg = (data) => {
  query.orgId = data.id; // 修改查询条件
  query.current = 1; // 重置页码为1
  getUserList(); // 刷新用户数据
};

// 获取用户数据
const getUserList = async () => {
  loading.value = true;
  const res = await getUsers(query).catch((e) => {
    loading.value = false;
  });
  userData.value = res.data.list;
  total.value = res.data.total;
  loading.value = false;
};
const reset = () => {
  query.userName = "";
  query.mobile = "";
  getUserList();
};
// 执行搜索
const handleSearch = () => {
  query.current = 1;
  getUserList();
};

// 展开详情
const expandUserDetail = ({ expanded, row }) => {
  if (!expanded) {
    return;
  }
  getUserInfo(row.id).then((res) => {
    const target = userData.value.find((item) => item.id === row.id);
    target.orgRoleList = res.data.orgRoleList;
  });
};

//
const handleRemove = async (item) => {
  const res = await removeUser(item.id);
  if (res.status === 200) {
    getUserList();
  }
};

const handleUnbindPhone = async (item) => {
  const res = await unbindPhone({
    ...item,
    userId: item.id,
  });
  if (res.status === 200) {
    getUserList();
  }
};
const resetPassword = async (row, password) => {
  const para = {
    orgRoles: row.orgRoles,
    password: password,
  };
  console.log(row, para);
  // const res = await editUser(para)
};
const handlePassword = (row) => {
  ElMessageBox.prompt(
    "请输入以字母开头的大于6位的数字与字母组成的密码",
    "设置密码",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputType: "password",
      inputPattern: /^[a-zA-Z][a-zA-Z0-9]{5,}$/,
      inputErrorMessage: "请输入正确的 密码",
    }
  ).then(({ value }) => {
    resetPassword(row, value);
  });
};
const sizeChange = (val) => {
  query.size = val;
  query.current = 1;
  getUserList();
};
onMounted(() => {
  getUserList();
});
</script>

<style lang="scss" scoped>
@import "../globle.scss";
footer {
  margin-top: 20px;

  :deep(.el-pagination) {
    text-align: right;
  }
}
:deep(.avatar-cell) {
  .vxe-cell {
    display: flex;
  }
}

.org-role-panel {
  background: #f5f7f9;
  border-radius: 5px;
  padding: 20px;
  padding-top: 10px;
  & > div {
    margin-bottom: 10px;
  }
}

.content {
  display: flex;
  height: calc(100vh - 255px);
  overflow: hidden;
  .org-tree {
    margin-right: 20px;
    width: 240px;
    height: 100%;
    background: #f6f9ff;
    overflow: scroll;
    :deep(.el-card),
    :deep(.el-card__body) {
      height: 100%;
    }
    :deep(.el-tree-node__content) {
      height: 50px;
    }
  }

  .table-card {
    height: calc(100% - 60px);
    flex: 1;

    :deep(.el-card),
    :deep(.el-card__body) {
      height: 100%;
    }
    h5 {
      background: #f5f7f9;
      padding: 10px 20px;
    }
  }
}
</style>
